/** Copyright (C) 2007 Pascal Richter
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package jlfm.lastfm.tools.url;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class UrlWrapper {

	private String server = "";

	private String protocol = "";

	private String file = "";

	private Map<String, String> queryMap = new HashMap<String, String>();

	private String buildQuery() {
		String query = "";

		Iterator<String> it = queryMap.keySet().iterator();
		int i = 1;
		while (it.hasNext()) {
			if (i == 1) {
				query += "?";
			}
			String key = it.next();
			query += encode(key) + "=" + encode(queryMap.get(key));
			
			if (i != queryMap.size()) {
				query += "&";
			}
			i++;
		}
		return query;
	}

	private String encode(String s) {
		try {
			return URLEncoder.encode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public void addQueryParameter(String key, String value) {
		queryMap.put(key, value);
	}

	public void removeQueryParameter(String key) {
		queryMap.remove(key);
	}

	public URL getURL() throws MalformedURLException {
		return new URL(getProtocol(), getServer(), getFile() + buildQuery());
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getServer() {
		return server;
	}

	public void setServer(String server) {
		this.server = server;
	}

}
